<?php
namespace App\Models;

class WechatAuth extends BaseModel
{
    protected $table = 'wechat_auths';

    public static function getOneByOpenid($unionid) {
        return self::where('openid', $unionid)->first();
    }

    public static function storeAuth($sessionKey, $openid, $unionid)
    {
        $m = self::getOneByOpenid($unionid);
        if (!$m) $m = new self();
        $m->session_key = $sessionKey;
        $m->openid      = $openid;
        $m->unionid     = $unionid;
        $m->save();
        return $m;
    }

    public function storeUserInfo(array $data)
    {
        $this->unionid   = $data['unionId'] ?? "";
        $this->nick_name = $data['nickName'] ?? "";
        $this->avatar    = $data['avatarUrl'] ?? "";
        $this->gender    = $data['gender'] ?? 0;
        $this->province  = $data['province'] ?? "";
        $this->city      = $data['city'] ?? "";
        $this->country   = $data['country'] ?? "";
        $this->avatar    = $this->avatar ? \Wechat::storeWechatAvatar($this->avatar) : "";
        $this->save();
        return $this->refresh();
    }
}
